package org.planaz.campusvoting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.planaz.campusvoting.common.result.Result;
import org.planaz.campusvoting.common.result.Results;
import org.planaz.campusvoting.mapper.ActivityMapper;
import org.planaz.campusvoting.mapper.HistoryMapper;
import org.planaz.campusvoting.mapper.ItemMapper;
import org.planaz.campusvoting.mapper.UserMapper;

import org.planaz.campusvoting.pojo.*;
import org.planaz.campusvoting.service.ActivityService;
import org.planaz.campusvoting.common.user.UserContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import static com.baomidou.mybatisplus.extension.toolkit.Db.*;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private HistoryMapper historyMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Result<?> publish(ActivityFilter activity) {
        Activity _activity = new Activity();
        _activity.setUid(UserContext.getUserId());
        _activity.setCover(activity.getCover());
        _activity.setPnum(0);
        _activity.setVnum(0);
        _activity.setView(0);
        _activity.setGenre(activity.getGenre());
        _activity.setIntro(activity.getIntro());
        if(activity.getState() == null)
            _activity.setState("Pending");
        else _activity.setState(activity.getState());
        _activity.setTittle(activity.getTittle());
        _activity.setStartTime(activity.getStartTime());
        _activity.setEndTime(activity.getEndTime());
        _activity.setPnum(activity.getList().size());
        save(_activity);
        // System.out.println(_activity.getId()); //查看是否生成了id
        // 创建完活动后添加参选人员

        for (Item listItem:activity.getList()) {
            listItem.setActId(_activity.getId());
        }
        saveBatch(activity.getList());
        return Results.success();
    }

    @Override
    public Result<?> list(ActivityFilter activityFilter) {

        if (activityFilter.getPage() == null) activityFilter.setPage(1);
        if (activityFilter.getSize() == null) activityFilter.setSize(10);

        Page<Activity> _page = new Page<>(activityFilter.getPage(), activityFilter.getSize());

        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(activityFilter.getGenre()!=null,"genre",activityFilter.getGenre());
        queryWrapper.eq(activityFilter.getStartTime()!=null,"start_time",activityFilter.getStartTime());
        queryWrapper.eq(activityFilter.getEndTime()!=null,"end_time",activityFilter.getEndTime());
        queryWrapper.like(activityFilter.getTittle()!=null,"tittle",activityFilter.getTittle());
        queryWrapper.eq(activityFilter.getState()!=null,"state",activityFilter.getState());

        Page<Activity> list = activityMapper.selectPage(_page,queryWrapper);
        return Results.success(list);
    }

    @Override
    public Result<?> mylist(Activity activity) {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        if(activity.getState() != null){
            queryWrapper.eq("state",activity.getState())
                    .eq("uid",UserContext.getUserId());
        }
        List<Activity> list = activityMapper.selectList(queryWrapper);
        return Results.success(list);
    }

    @Override
    public Result<?> modify(Activity activity) {
        UpdateWrapper<Activity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",activity.getId());
        updateWrapper.set(activity.getGenre() != null,"genre",activity.getGenre());
        updateWrapper.set(activity.getStartTime() != null,"start_time",activity.getStartTime());
        updateWrapper.set(activity.getEndTime() != null,"end_time",activity.getEndTime());
        updateWrapper.set(activity.getTittle() != null,"tittle",activity.getTittle());
        updateWrapper.set(activity.getIntro() != null,"intro",activity.getIntro());
        updateWrapper.set(activity.getCover() != null,"cover",activity.getCover());
        updateWrapper.set(activity.getState() != null,"state",activity.getState());
        updateWrapper.set(activity.getPnum() != null,"pnum",activity.getPnum());
        updateWrapper.set(activity.getVnum() != null,"vnum",activity.getVnum());
        return Results.success(activityMapper.update(updateWrapper));
    }

    @Override
    public Result<?> add(Item item) {
        Item _item = new Item();
        _item.setActId(item.getActId());
        _item.setNum(0);
        _item.setCover(item.getCover());
        _item.setIntro(item.getIntro());
        _item.setTittle(item.getTittle());
        if(item.getUid()!=null)
            _item.setUid(item.getUid());
        else
            _item.setUid(UserContext.getUserId());

        if(item.getState() != null) _item.setState(item.getState());
        save(_item);

        //附加操作：给活动表的pnum参选人数加1
        UpdateWrapper<Activity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",item.getActId());
        updateWrapper.setSql("pnum = pnum + 1");
        activityMapper.update(updateWrapper);
        return Results.success();
    }

    @Override
    public Result<?> all(ItemFilter itemFilter) {
        if (itemFilter.getPage() == null) itemFilter.setPage(1);
        if (itemFilter.getSize() == null) itemFilter.setSize(10);

        Page<Item> _page = new Page<>(itemFilter.getPage(), itemFilter.getSize());

        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("act_id",itemFilter.getActId());
        queryWrapper.like(itemFilter.getTittle()!=null,"tittle",itemFilter.getTittle()) ;
        queryWrapper.eq(itemFilter.getState()!=null,"state",itemFilter.getState());
        queryWrapper.ge(itemFilter.getNum()!=null,"num",itemFilter.getNum());
        queryWrapper.orderByAsc(itemFilter.getOrder()!=null && itemFilter.getOrder()==1,"num");
        queryWrapper.orderByDesc(itemFilter.getOrder()!=null && itemFilter.getOrder()==2,"num");
        //还需要添加用户名和头像
        Page<Item> items = itemMapper.selectPage(_page,queryWrapper);
//        for (Item item : items.getRecords()){
//            User user = userMapper.selectById(item.getUid());
//            //System.out.println(item.getUid());
//            item.setAvatar(user.getAvatar());
//            item.setUsername(user.getUsername());
//        }
        return Results.success(items);
    }

    @Override
    public Result<?> like(Long id) {

        UpdateWrapper<Item> updateWrapperItem = new UpdateWrapper<>();
        updateWrapperItem.eq("id",id);
        updateWrapperItem.setSql(" num = num+1");
        itemMapper.update(updateWrapperItem);

        //附加操作，给活动表中的vnum+1
        UpdateWrapper<Activity> updateWrapperActivity = new UpdateWrapper<>();

        //查询对应的actId
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Long actId = itemMapper.selectOne(queryWrapper).getActId();

        updateWrapperActivity.eq("id",actId);
        updateWrapperActivity.setSql(" vnum = vnum+1");
        activityMapper.update(updateWrapperActivity);

        //附加操作：在history表中新建字段
        History history = new History();
        history.setUid(UserContext.getUserId());
        history.setVid(id);
        history.setAid(actId);
        save(history);

        return Results.success();
    }
    @Override
    public Result<?> unlike(Long id) {

        UpdateWrapper<Item> updateWrapperItem = new UpdateWrapper<>();
        updateWrapperItem.eq("id",id);
        updateWrapperItem.setSql(" num = num-1");
        itemMapper.update(updateWrapperItem);

        //附加操作，给活动表中的vnum-1
        UpdateWrapper<Activity> updateWrapperActivity = new UpdateWrapper<>();

        //查询对应的actId
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Long actId = itemMapper.selectOne(queryWrapper).getActId();

        updateWrapperActivity.eq("id",actId);
        updateWrapperActivity.setSql(" vnum = vnum-1");
        activityMapper.update(updateWrapperActivity);

        //附加操作：在history表中删除字段
        QueryWrapper<History> queryWrapperHistory = new QueryWrapper<>();
        queryWrapperHistory.eq("vid",id);
        historyMapper.delete(queryWrapperHistory);
        return Results.success();
    }
    @Override
    public Result<?> modifyCandidate(Item item) {
        UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",item.getId());
        updateWrapper.set(item.getCover()!=null,"cover",item.getCover());
        updateWrapper.set(item.getIntro()!=null,"intro",item.getIntro());
        updateWrapper.set(item.getTittle()!=null,"tittle",item.getTittle());
        updateWrapper.set(item.getState()!=null,"state",item.getState());
        updateWrapper.set(item.getCause()!=null,"cause",item.getCause());
        return Results.success(itemMapper.update(updateWrapper));
    }

    @Override
    public Result<?> deleteA(Long id) {
        activityMapper.deleteById(id);
        //删除所有该活动的参与者
        Map<String,Object> map = new HashMap<>();//"act_id",id
        map.put("act_id",id);
        itemMapper.deleteByMap(map);
        return Results.success();
    }

    @Override
    public Result<?> deleteI(Long id) {
        return Results.success(itemMapper.deleteById(id));
    }


    //查看我投票过的活动和报名过的活动
    @Override
    public Result<?> myVote(Long id) {
        //根据我自己的uid查询history表中所有的项，然后根据vid在item表中查询选手
        QueryWrapper<History> queryWrapperHistory = new QueryWrapper<>();
        if (id == null) id = UserContext.getUserId();
        queryWrapperHistory.eq("uid",id);
        List<History> historyList = historyMapper.selectList(queryWrapperHistory);

        List<Item> itemList = new ArrayList<>();
        for(History history : historyList){
            itemList.add(itemMapper.selectById(history.getVid()));
        }
        return Results.success(itemList);
    }
    @Override
    public Result<?> myEnter(Long id) {
        //根据我自己的uid查询Activity表中所有的项
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        if (id == null) id = UserContext.getUserId();
        queryWrapper.eq("uid",id);
        List<Item> list = itemMapper.selectList(queryWrapper);

        return Results.success(list);
    }
    @Override
    public Result<?> myVoteAct(Long id) {
        //根据我自己的uid查询history表中所有的项，然后根据aid在Act表中查询活动
        QueryWrapper<History> queryWrapperHistory = new QueryWrapper<>();
        if (id == null) id = UserContext.getUserId();
        queryWrapperHistory.eq("uid",id);
        List<History> historyList = historyMapper.selectList(queryWrapperHistory);

        List<Activity> activityList = new ArrayList<>();
        for(History history : historyList){
            activityList.add(activityMapper.selectById(history.getAid()));
        }
        return Results.success(activityList);
    }

    @Override
    public Result<?> allvote(Long actId) {
        //在历史表中根据actid查询所有的uid，再去uid查询所有的用户
        QueryWrapper<History> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("aid",actId);
        List<History> list = historyMapper.selectList(queryWrapper);
        List<User> userList = new ArrayList<>();
        for(History l : list){
            User u = userMapper.selectById(l.getUid());
            userList.add(u);
        }
        return Results.success(userList);
    }

    @Override
    public Result<?> activityDetail(Long actId) {
        Activity activity=activityMapper.selectOne(Wrappers.<Activity>lambdaQuery().eq(Activity::getId,actId));
        activity.setView(activity.getView()+1);
        activityMapper.update(activity,Wrappers.<Activity>lambdaQuery().eq(Activity::getId,actId));
        return Results.success(activity);
    }

}
